from flask import *
from flask_sqlalchemy import SQLAlchemy
import click
from flask_migrate import Migrate
from werkzeug.security import generate_password_hash, check_password_hash
import os
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required

app = Flask(__name__)

HOSTNAME = "127.0.0.1"  # 
PORT = 3306
USERNAME = "root"
PASSWORD = "xxx" #自己的用户名和密码
DATABASE = "database_learn"

app.config[
    'SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8"

db = SQLAlchemy(app)

migrate = Migrate(app, db)
app.secret_key = os.urandom(20)
login_manager = LoginManager(app)

login_manager.login_view = 'home'


# login_manager.login_message = "需要先登录"

class User(db.Model, UserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # nullable 不能为空
    username = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(100))

    def set_password(self, password):
        self.password = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password, password)


# with app.app_context():
#     db.create_all()


@app.route('/')
def home():
    return render_template("home.html")


@app.route("/user/add", methods=['GET', 'POST'])
@login_required
def add_user():
    if request.method == 'POST':
        user1 = User(username=request.form.get("name"), email=request.form.get("email"))
        user1.set_password(request.form.get("password"))

        db.session.add(user1)

        db.session.commit()
    return render_template("add.html")


@app.route("/user/query", methods=['GET', 'POST'])
@login_required
def query_user():
    # 1.get查找
    # user = User.query.get(1)
    # print(f"{user.id}:{user.username}:{user.password}")
    # return "数据查找成功"
    # 2.filter_by查找
    if request.method == 'POST':
        x = User.query.filter_by(username=request.form.get("name")).first()
        return redirect(url_for('user', email=x.email))
    # for user in users:
    #     print(user.username, user.password)
    return render_template("query.html")


@app.route("/user/show")
@login_required
def show_user():
    users = User.query.filter_by()
    return render_template("show.html", users=users)


@app.route("/user/update", methods=['GET', 'POST'])
@login_required
def update_user():
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form.get("name")).first()

        user.set_password(request.form.get("password"))
        db.session.commit()
    return render_template("update.html")


@app.route("/user/delete", methods=['GET', 'POST'])
@login_required
def delete_user():
    # 1、查找
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form.get("name")).first()
        # 2、从db.session中删除
        db.session.delete(user)
        # 3、同步
        db.session.commit()
    return render_template("delete.html")


@app.route("/user/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get("name")
        password = request.form.get("password")
        flag = 0
        users = User.query.filter_by()
        for x in users:
            if x.username == username and x.validate_password(password):
                user = x
                flag = 1
        if (flag == 1):
            # flash("登陆成功")
            login_user(user)
            return redirect(url_for("home"))

        flash("验证失败")
        return redirect(url_for("login"))

    return render_template("login.html")


@app.route("/user/index")
def index_user():
    return render_template("index.html")


@app.route("/user/?<string:email>")
def user(email):
    return email


@app.route("/user/update-email", methods=['GET', 'POST'])
@login_required
def update_user_email():
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form.get("name")).first()

        user.email = request.form.get("email")
        db.session.commit()
    return render_template("update_email.html")


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user1 = User(username=request.form.get("name"), email=request.form.get("email"))
        user1.set_password(request.form.get("password"))

        db.session.add(user1)

        db.session.commit()
        return redirect(url_for("home"))
        # login_user(user)
    return render_template("register.html")


@app.route('/logout')
@login_required
def logout():
    logout_user()
    # flash('logout')
    return redirect(url_for("home"))


@login_manager.user_loader
def load_user(user_id):
    user = User.query.get(int(user_id))

    return user


@app.errorhandler(AttributeError)
def error(e):
    user = User.query.first()
    return render_template('error.html', user=user)


with app.app_context():
    @app.cli.command()
    @click.option('--username', prompt=True, help='The username used to login.')
    @click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True,
                  help='The password used to login.')
    def admin(username, password):

        user = User.query.get(1)
        if user is not None:
            click.echo('Updating user...')
            user.username = username
            user.set_password(password)  # 设置密码
        else:
            click.echo('Creating user...')
            user = User(username=username)
            user.set_password(password)  # 设置密码
            db.session.add(user)


    db.session.commit()  # 提交数据库会话
    click.echo('Done.')

if __name__ == '__main__':
    app.run()
